<template>
	<view class="rtcLive">
		<view class="pageTop align-center flexrow justify-between" style="width: 100vw;top: 0;">
			<uni-icons style="margin-left: 20rpx;" @click="pushback()" type="back" size="30" color="#FFF"></uni-icons>
			<view class="pageTopCenter">
				<view><text style="font-size: 26rpx;color: #FFFFFF;">央清1班</text></view>
				<view><text style="font-size: 22rpx;color: #CACACA;">央清1班</text></view>
			</view>
			<view @click="hangup"><text class="finish">结束</text></view>
		</view>
		<video style="width: 100vw;height: calc(100vh - 88rpx);" id="localVideo" ref="localVideo" src="videosrc" controls autoplay="autoplay"></video>
		
		<cover-view style="z-index: 999999;display: flex;" class="bottomHandle" :style="{width: systemInfo.screenWidth + 'px'}">
			<view class="bottomHandleList" @click="liveMuted = !liveMuted;delVideoTrack()">
				<image class="bottomIcon" src="/static/image/mk.png" mode=""></image>
				<text style="color: #D8D8D8;font-size: 22rpx;">{{liveMuted ? '静音' : '关闭静音'}}</text>
			</view>
			<view class="bottomHandleList" @click="liveCamera = !liveCamera">
				<image class="bottomIcon" src="/static/image/live.png" mode=""></image>
				<text style="color: #D8D8D8;font-size: 22rpx;">{{liveCamera ? '关闭' : '开启'}}</text>
			</view>
			<view class="bottomHandleList" @click="switchCamera">
				<image class="bottomIcon" src="/static/image/xj.png" mode=""></image>
				<text style="color: #D8D8D8;font-size: 22rpx;">切换</text>
			</view>
			<view class="bottomHandleList" @click="seeMember">
				<image class="bottomIcon" src="/static/image/member.png" mode=""></image>
				<text style="color: #D8D8D8;font-size: 22rpx;">成员</text>
			</view>
			<view class="bottomHandleList" @click="changeLiveO">
				<image class="bottomIcon" src="/static/image/xz.png" mode=""></image>
				<text style="color: #D8D8D8;font-size: 22rpx;">旋转</text>
			</view>
		</cover-view>
		
		
		<uni-popup type='bottom' ref="classroom">
			<view class="classroomView" :style="{width: systemInfo.screenWidth + 'px'}">
				<view class="classroomViewTop" :style="{width: systemInfo.screenWidth + 'px'}">
					<view class="classroomViewTopCenter">
						<view class="classroomViewTopCenterLeft">
							<scroll-view scroll-y="true" style="height: 100%;">
								<view @click="handleClass(im,ix)" v-for="(im,ix) in classList" style="align-items: center;flex-direction: row;margin-bottom: 10rpx;">
									<view :class="im.isCheckAll || im.isCheck ? 'isCheckRoom' : 'checkRoom'" style="width: 38rpx;height: 38rpx;border-radius: 50%;align-items: center;justify-content: space-around;">
										<uni-icons v-if="im.isCheckAll" type="checkmarkempty" size="15" color="#FFF"></uni-icons>
										<text v-if="!im.isCheckAll && im.isCheck" style="font-size: 50rpx;color: #FFFFFF;">-</text>
									</view>
									<text style="margin-left: 20rpx;">{{im.name}}</text>
								</view>
							</scroll-view>
						</view>
						<view class="classroomViewTopCenterRight">
							<scroll-view scroll-y="true" style="height: 100%;">
								<view @click="handleStudent(im)" v-for="im in allClassStudentData[checkClassIndex]" style="align-items: center;flex-direction: row;margin-bottom: 10rpx;">
									<view :class="im.isCheck ? 'isCheckRoom' : 'checkRoom'" style="width: 38rpx;height: 38rpx;border-radius: 50%;align-items: center;justify-content: space-around;">
										<uni-icons v-if="im.isCheck" type="checkmarkempty" size="15" color="#FFF"></uni-icons>
									</view>
									<text style="margin-left: 20rpx;">{{im.yStudent.name}}</text>
								</view>
							</scroll-view>
						</view>
					</view>
				</view>
				<view style="height: 8rpx;background-color: #F7F7F7;" :style="{width: systemInfo.screenWidth + 'px'}"></view>
				<view @click.stop="invitaton" style="display: flex;flex: 1;height: 100rpx;align-items: center;justify-content: space-around;position: relative;z-index: 99999"><text style="font-size: 36rpx;color: #2E2E2E;">确定</text></view>
			</view>
		</uni-popup>
		
	</view>
</template>

<script>
	var ws = new WebSocket('ws://localhost:3030');
	import * as api from '@/utils/api.js'
	export default{
		name: "rtcLive",
		data() {
			return {
				title: 'Hello',
				wsKey: null,
				peerListObject: {},
				stream: null,
				localStream: null,
				localStreamBack: null,
				peerConnA: null,
				peerConnB: null,
				localVideo: null,
				videosrc: null,
				systemInfo:{},
				floatStyle: {
					left: '0px',
					top: '20px'
				},
				showTB: true,
				liveMuted: true,
				isLiving: false,
				liveCamera: true,
				liveOrientation: 'vertical',
				classList: [],
				allClassStudentData: [],
				allClassStudentCheckData: [],
				checkClassIndex: 0,
				checkclassListIndex: 0,
				classIdS: [],
				
			}
		},
		onLoad() {
			const self = this
			const that = this
			uni.getSystemInfo({
				success: res => {
					that.systemInfo = res
				}
			})
			this.getData()
			this.localVideo = uni.createVideoContext('localVideo')
			ws.onopen = function(evt) {
				console.log('Connection open ...');
				self.listenMessage()
				self.initStream()
			};
		},
		methods: {
			delVideoTrack(){
				const self = this
				if(!this.liveMuted){
					console.log('removeTrack')
					this.localStream.removeTrack(this.localStream.getAudioTracks()[0])
				}else{
					console.log('addTrack')
					navigator.mediaDevices.getUserMedia({
						video: true,
						audio: true
					}).then(res => {
						self.localStream.addTrack(res.getAudioTracks()[0])
					}).catch(err => console.log(err))
					
				}
			},
			
			getData(){
				const self = this
				api.getYClassList().then( res => {
					res.data.list.forEach((im,ix) => {
						im.isCheckAll = false
						im.isCheck = false
						self.allClassStudentData.push([])
						self.allClassStudentCheckData.push([])
					})
					self.classList = res.data.list
					self.getClassStudent(0)
				})
			},
			getClassStudent(index){
				const self = this
				api.getYClassStudentList({
					classId: self.classList[index].ID
				}).then( res => {
					res.data.list.forEach((im,ix) => {
						im.isCheck = false
					})
					self.allClassStudentData[index] = res.data.list
					self.$forceUpdate()
				})
			},
			// 点击选中或者取消选中学生
			handleStudent(im){
				// 取反 选中
				im.isCheck = !im.isCheck
				
				// 判断当前的学生选中数组中有没有当前学生id 没有则添加 有则删除
				let tempIndex = this.allClassStudentCheckData[this.checkClassIndex].indexOf(im.studentId)
				tempIndex == -1 ? this.allClassStudentCheckData[this.checkClassIndex].push(im.studentId) : this.allClassStudentCheckData[this.checkClassIndex].splice(tempIndex, 1)
				
				this.handleIsCheckAll()
			},
			// 判断当前班级的学生是否全部被选中
			handleIsCheckAll(){
				
				// 判断是否全选
				this.classList[this.checkClassIndex].isCheckAll = this.allClassStudentData[this.checkClassIndex].length == this.allClassStudentCheckData[this.checkClassIndex].length ? true : false
				
				// 判断选中的学生中是否有当前班级的
				this.classList[this.checkClassIndex].isCheck = this.allClassStudentCheckData[this.checkClassIndex].length ? true : false
				
				// 添加当全学生当班级
				let isAddClassId = this.classIdS.indexOf(this.classList[this.checkClassIndex].ID)
				
				if(this.classList[this.checkClassIndex].isCheck){
					if(isAddClassId == -1){
						this.classIdS.push(this.classList[this.checkClassIndex].ID)
					}
				}else{
					if(isAddClassId != -1){
						this.classIdS.splice(isAddClassId, 1)
					}
				}
				
				// 更新视图
				this.$forceUpdate()
			},
			handleClass(im,ix){
				this.checkClassIndex = ix
				this.handleIsCheckAll()
				if(this.allClassStudentData[this.checkClassIndex].length) return
				
				this.getClassStudent(this.checkClassIndex)
			},
			
			
			
			// 确认邀请
			invitaton(){
				let arr = []
				this.allClassStudentCheckData.forEach(im => {
					arr.push(...im)
				})
				let params = {
					classIds: this.classIdS,
					studentIds: arr,
					channelId: 1,
					typeValue: 1
				}
				api.createYLiveStudents(params).then( res => {
					console.log(res)
					if(!res.code){
						uni.showToast({
							title: '成功发送邀请',
							icon: 'success'
						})
						this.$refs.classroom.close()
					}
				})
			},
			seeMember(){
				console.log('===aa')
				this.$refs.classroom.open()
				// this.$refs.membersPop.open()
			},
			changeLiveO(){
				
			},
			switchCamera(){
				
			},
			
			
			
			
			
			pushback(){uni.navigateBack()},
			async sendOffer(data){
				console.log(data,'datadata')
				const self = this
				let configuration = {"iceServer": [{"url": "stun: stun.l.google.com:19302"}]}
				// 一对一
				self.peerConnA = new RTCPeerConnection(configuration)
			
				//一对多
				// peerListObject[data] = new RTCPeerConnection(configuration)
				self.peerListObject[data] = self.peerConnA
				self.peerConnA.addEventListener('icecandidate', self.onIceCandidDateA)
				self.peerConnA.addEventListener('iceconnectionstatechange', self.onIceStateChangeA)
			
				// A 将流添加至 peerConnA
				self.localStream.getTracks().forEach(track => {
					self.peerConnA.addTrack(track, self.localStream)
				})
			
				try{
					const offer = await self.peerConnA.createOffer()
					console.log(offer,'offerofferofferofferoffer')
					await self.onCreateOfferSuccess(offer)
				}catch (e) {
				}
			
			},
			async onCreateOfferSuccess(desc){
				const self = this
				try{
					// 设置本地描述
					await self.peerConnA.setLocalDescription(desc)
					self.onSetLocalSuccess(self.peerConnA)
			
					let obj = JSON.stringify({
						type: 'createOffer',
						data: desc
					})
			
					ws.send(obj);
			
				}catch (e) {
					console.log(e,'onCreateOfferSuccessonCreateOfferSuccessonCreateOfferSuccessonCreateOfferSuccess')
				}
			},
			async onSetLocalSuccess(){
				console.log('本地流设置完成')
			},
			async onIceCandidDateA(evt){
				const sefl = this
			
				try{
					if(evt.candidate){
			
						let candObj = JSON.stringify({
							type: 'candidateToB',
							data: evt.candidate
						})
			
						ws.send(candObj)
					}
			
				}catch (e){console.log(e)}
			},
			async candidateToA(data, key){
				console.log(data, key,'data, keydata, keydata, keydata, key')
				const sefl = this
				try{
					await sefl.peerListObject[key].addIceCandidate(data)
					sefl.onAddIceCandidateSuccess(self.peerConnA)
				}catch (e){}
			},
			hangup(){
				this.peerConnA.close()
				this.peerConnB.close()
				this.peerConnA = null
				this.peerConnB = null
			},
			initStream() {
				const self = this
				let myVideo = document.querySelector('#localVideo video')
				navigator.mediaDevices.getUserMedia({
					video: true,
					audio: true
				}).then(res => {
					console.log(res,'====')
					myVideo.srcObject = res
					myVideo.play()
					self.localStream = res
					self.localStreamBack = res
					
				}).catch(err => console.log(err))
			},
			async pcaSetRemote(data, key){
				const self = this
				try{
					await self.peerListObject[key].setRemoteDescription(data)
				}catch (e) {
					console.log(e)
				}
			},
			listenMessage(){
				const self = this
				ws.onmessage = function(evt) {
				
					let tempData = JSON.parse(evt.data)
					
					console.log(tempData.type)
				
					switch (tempData.type){
						case 'backAnswer':
							self.pcaSetRemote(tempData.data, tempData.key)
							break
						case 'candidateToA':
							self.candidateToA(tempData.data, tempData.key)
							break
						case 'mainSendOffer':
							self.sendOffer(tempData.data)
							break
						case "backKey":
							self.wsKey = tempData.data
							break
					}
				
				};
				
				ws.onclose = function(evt) {
					console.log('Connection closed.');
				};
			}
		}
	}
</script>

<style lang="scss" scoped>
	.rtcLive{
		
			.checkRoom{
				border: 2rpx solid #EEEEEE;
			}
			.isCheckRoom{
				background-color: #FC2C1C;
			}
			.classroomViewTopCenterLeft{
				width: 290rpx;
				height: 100%;
				border-right: 1rpx solid #D8D8D8;
				// background: #f00;
			}
			.classroomViewTopCenterRight{
				width: 290rpx;
				height: 100%;
				margin-left: 30rpx;
			}
			.classroomViewTopCenter{
				display: flex;
				flex: 1;
				margin-left: 80rpx;
				margin-right: 80rpx;
				height: 351rpx;
				flex-direction: row;
				align-items: center;
				justify-content: space-between;
			}
			.classroomViewTop{
				// height: 480rpx;
				align-items: center;
				flex-direction: row;
			}
			.classroomView{
				height: 590rpx;
				background: #fff;
				border-top-left-radius: 30rpx;
				border-top-right-radius: 30rpx;
			}
			.allMemberBtns{
				flex-direction: row;
				align-items: center;
				justify-content: space-between;
				height: 98rpx;
			}
			.allMemberTop{
				height: 128rpx;
				align-items: center;
				justify-content: space-around;
				border-bottom: 1rpx solid #D8D8D8;
			}
			.inviteView{
				.inviteViewList{
					margin-left: 20rpx;
					margin-right: 20rpx;
					border-radius: 18rpx;
					height: 203rpx;
					background: #fff;
					align-items: center;
				}
				.inviteViewCancle{
					margin-left: 20rpx;
					margin-right: 20rpx;
					border-radius: 18rpx;
					height: 100rpx;
					background: #fff;
					margin-top: 8rpx;
					margin-bottom: 38rpx;
					align-items: center;
					justify-content: space-around;
				}
			}
			.memberListBottomhandleListBtn{
				width: 217rpx;
				height: 86rpx;
				border: 1rpx solid #979797;
				align-items: center;
				justify-content: space-around;
				margin-top: 20rpx;
			}
			.memberListBottomhandleList{
				height: 130rpx;
				border-top: 1rpx solid #ccc;
				align-items: center;
				flex-direction: row;
				justify-content: space-around;
			}
			.memberListBottomListRight{
				align-items: center;
				flex-direction: row;
			}
			.memberListBottomList{
				align-items: center;
				flex-direction: row;
				justify-content: space-between;
				margin-left: 23rpx;
				margin-right: 23rpx;
				height: 104rpx;
				border-bottom: 1rpx solid #F6F6F6;
			}
			.memberListBottomListLeft{
				flex-direction: row;
				align-items: center;
			}
			.memberListTopSearch{
				width: 679rpx;
				height: 66rpx;
				border-radius: 30rpx;
				background: #F7F7F7;
				margin-top: 32rpx;
				align-items: center;
				flex-direction: row;
				justify-content: space-between;
			}
			.memberListTopTitle{
				flex-direction: row;
				align-items: center;
				justify-content: space-between;
				margin-top: 57rpx;
			}
			.memberList{
				height: 1200rpx;
				background: #fff;
				border-top-left-radius: 43rpx;
				border-top-right-radius: 43rpx;
				.memberListTop{
					height: 280rpx;
					align-items: center;
					border-bottom: 1rpx solid #ccc;
				}
				.memberListBottom{
					height: 870rpx;
				}
			}
			position: relative;
			flex-direction: column;
			.floatView{
				position: fixed;
				width: 159rpx;
				height: 220rpx;
				background: #0ff;
			}
			.bottomHandleList{
				display: flex;
				margin-top: 10rpx;
				margin-left: 50rpx;
				margin-right: 50rpx;
				flex-direction: column;
				align-items: center;
				justify-content: space-around;
				height: 80%;
			}
			.bottomIcon{
				width: 50rpx;
				height: 50rpx;
			}
			.bottomHandle{
				position: absolute;
				bottom: 0;
				left: 0;
				width: 100%;
				// width: 300px;
				height: 118rpx;
				background: #232426;
				align-items: center;
				justify-content: space-between;
				flex-direction: row;
				z-index: 999;
			}
			.flexrow{flex-direction: row;}
			.pageTop{
				display: flex;
				// flex: 1;
				height: 88rpx;
				background: #232426;
				align-items: center;
				justify-content: space-between;
				z-index: 999;
			}
			.backBtn{
				font-size: 36rpx;
				color: #FFFFFF;
			}
			.finish{
				font-size: 30rpx;
				color: #FC2C1C;
				margin-right: 18px;
			}
			.pageTopCenter{
				align-items: center;
			}
	}
</style>
